package com.atguigui.leetcode;

/**
 * 956.验证外星语词典
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by WJX on 2022/5/17 9:21
 */
public class P953VerifyingAnAlienDictionary {
    public static void main(String[] args) {
        Solution solution = new P953VerifyingAnAlienDictionary().new Solution();
        // TO TEST
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public boolean isAlienSorted(String[] words, String order) {
            int[] index = new int[26];
            for (int i = 0; i < order.length(); ++i) {
                index[order.charAt(i) - 'a'] = i;
            }

            for (int i = 1; i < words.length; i++) {
                boolean valid = false;
                // 判断不超过2个字符的长度
                for (int j = 0; j < words[i - 1].length() && j < words[i].length(); j++) {
                    int prev = index[words[i - 1].charAt(j) - 'a'];
                    int curr = index[words[i].charAt(j) - 'a'];
                    if (prev < curr) {
                        valid = true;
                        break;
                    } else if (prev > curr) {
                        return false;
                    }
                }
                if (!valid) {
                    /* 比较两个字符串的长度来判断大小 */
                    if (words[i - 1].length() > words[i].length()) {
                        return false;
                    }
                }
            }
            return true;
        }
    }
}
